package com.lebang.controller.buss;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lebang.common.ExeclUtil;
import com.lebang.common.Login;
import com.lebang.common.util.AmountUtil;
import com.lebang.component.AsyncsComponent;
import com.lebang.component.CommonComponent;
import com.lebang.component.MultiwordComponent;
import com.lebang.component.RedisClient;
import com.lebang.entity.member.LbbMember;
import com.lebang.entity.member.LbbMemberRecord;
import com.lebang.entity.task.LbbCommon;
import com.lebang.entity.task.TaskScreenshot;
import com.lebang.example.TaskClassifyExample;
import com.lebang.example.TaskTagExample;
import com.lebang.model.enums.Booleans;
import com.lebang.model.enums.Status;
import com.lebang.model.enums.buss.RewardMode;
import com.lebang.model.enums.buss.RewardType;
import com.lebang.model.enums.buss.TaskCategory;
import com.lebang.model.enums.buss.TaskStatus;
import com.lebang.model.vo.buss.TaskSearchVo;
import com.lebang.model.vo.buss.multiword.MultiwordSpeech;
import com.lebang.model.vo.buss.multiword.MultiwordSpeechPlan;
import com.lebang.service.MemberNoticeService;
import com.lebang.service.TaskClassifyService;
import com.lebang.service.TaskScreenshotService;
import com.lebang.service.TaskTagService;
import com.lebang.service.buss.CustomService;
import com.lebang.service.buss.MemberRecordService;
import com.lebang.service.buss.MemberService;
import com.lebang.service.buss.WalletService;
import com.lebang.service.task.TaskService;
import com.lebang.service.task.impl.MultiwordServiceImpl;
import com.lebangweb.common.DateUtil;
import com.lebangweb.common.TextUtil;
import com.lebangweb.common.UUIDUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;

@Controller
@RequestMapping("/multiword")
public class MultiwordController {

    @Autowired
    private CommonComponent commonComponent;

    @Autowired
    private MemberRecordService memberRecordService;

    @Autowired
    private WalletService walletService;

    @Autowired
    private AsyncsComponent asyncs;

    @Autowired
    private MemberService memberService;
    @Autowired
    private MultiwordServiceImpl multiwordServiceImpl;
    @Autowired
    private CustomService customService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    @Qualifier(value = "commonTaskService")
    private TaskService<LbbCommon> commonTaskService;
    @Autowired
    private MultiwordComponent multiwordComponent;
    @Autowired
    private MemberNoticeService memberNoticeService;
    @Autowired
    private TaskScreenshotService taskScreenshotService;
    @Autowired
    private TaskClassifyService taskClassifyService;
    @Autowired
    private TaskTagService taskTagService;

    /**
     * 列表入口
     *
     * @param model
     * @param session
     * @return
     * @author weizx
     * @date 2018年8月24日 下午2:34:32
     */
    @Login
    @RequestMapping(value = {"/list"}, method = {RequestMethod.GET})
    public String list(Model model, HttpSession session) {
        model.addAttribute("booleans", Booleans.values());
        model.addAttribute("rewards", RewardMode.values());
        model.addAttribute("types", RewardType.values());
        model.addAttribute("Status", Status.values());
        return "/multiword/list";
    }

    /**
     * 列表接口
     *
     * @param vo
     * @param request
     * @param response
     * @return
     * @author weizx
     * @date 2018年8月24日 下午2:34:39
     */
    @Login
    @RequestMapping(value = {"/list"}, method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> pagging(TaskSearchVo vo, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> data = commonComponent.pagging(vo, 1);
        return data;
    }

    @Login
    @RequestMapping(value = {"/status"}, method = {RequestMethod.POST})
    @ResponseBody
    public String status(@RequestParam(value = "taskid") String taskid, HttpServletRequest request,
                         HttpServletResponse response) {
        LbbCommon task = commonTaskService.taskInfoByTaskId(taskid);
        if (task == null) {
            return "任务不存在！";
        }
        if (task.getStatus().equals(Status.Off)) {
            task.setStatus(Status.On);
        } else {
            task.setStatus(Status.Off);
        }
        commonTaskService.updateTask(task);
        return "状态已修改！";
    }

    @Login
    @RequestMapping(value = {"/del"}, method = {RequestMethod.POST})
    @ResponseBody
    public String del(@RequestParam(value = "taskid") String taskid, HttpServletRequest request,
                      HttpServletResponse response) {
        LbbCommon task = commonTaskService.taskInfoByTaskId(taskid);
        if (task == null) {
            return "任务不存在！";
        }
        commonTaskService.deleteTask(task);
        return "已删除！";
    }

    @Login
    @RequestMapping(value = {"/dels"}, method = {RequestMethod.POST})
    @ResponseBody
    public String dels(@RequestParam(value = "memberId") String memberId, @RequestParam(value = "taskId") String taskId,
                       @RequestParam(value = "status") String status, HttpServletRequest request, HttpServletResponse response) {
        LbbMemberRecord mr = memberRecordService.getByMemberIdandTaskid(taskId, memberId, TaskStatus.CheckFailure.name());// 未审核的用户

        if (mr == null) {
            return "号码不存在！";
        }
        mr.setRemark(TaskStatus.None.name());
        memberRecordService.updateRecord(mr);
        return "已剔除！";
    }

    @Login
    @RequestMapping(value = {"/insert"}, method = {RequestMethod.GET})
    public String insert(Model model, HttpSession session) {
        model.addAttribute("rewards", RewardMode.values());
        model.addAttribute("types", RewardType.values());
        model.addAttribute("customlist", customService.getAllCustomList());
        TaskClassifyExample taskClassifyExample = new TaskClassifyExample();
        taskClassifyExample.createCriteria().andEnableEqualTo(1).andHasDeletedEqualTo("False");
        TaskTagExample taskTagExample = new TaskTagExample();
        taskTagExample.createCriteria().andEnableEqualTo(1).andHasDeletedEqualTo("False");
        model.addAttribute("taskClassifys",taskClassifyService.selectByExample(taskClassifyExample));
        model.addAttribute("taskTags",taskTagService.selectByExample(taskTagExample));
        return "/multiword/edit";
    }

    @Login
    @RequestMapping(value = {"/edit/{taskid}"}, method = {RequestMethod.GET})
    public String edit(@PathVariable(value = "taskid") String taskid, Model model, HttpSession session) {
        model.addAttribute("rewards", RewardMode.values());
        model.addAttribute("types", RewardType.values());
        LbbCommon task = commonTaskService.taskInfoByTaskId(taskid);
        TaskScreenshot taskScreenshot = taskScreenshotService.selectByTaskId(taskid);
        model.addAttribute("tags",taskScreenshotService.selectRelation(taskid));
        model.addAttribute("taskScreenshot",taskScreenshot);
        model.addAttribute("task", task);
        model.addAttribute("customlist", customService.getAllCustomList());
        TaskClassifyExample taskClassifyExample = new TaskClassifyExample();
        taskClassifyExample.createCriteria().andEnableEqualTo(1).andHasDeletedEqualTo("False");
        TaskTagExample taskTagExample = new TaskTagExample();
        taskTagExample.createCriteria().andEnableEqualTo(1).andHasDeletedEqualTo("False");
        model.addAttribute("taskClassifys",taskClassifyService.selectByExample(taskClassifyExample));
        model.addAttribute("taskTags",taskTagService.selectByExample(taskTagExample));
        return "/multiword/edit";
    }

    @Login
    @PostMapping(value = "/edit/multiword")
    @ResponseBody
    public JsonData multiwordlist(String taskid) {
        LbbCommon task = commonTaskService.taskInfoByTaskId(taskid);
        List<Map<String, Object>> list = multiwordComponent.selectMultiwordById(task.getId());
        if (list.size() > 0) {
            return Callback.success("200", "获取成功", list);
        } else {
            return Callback.fail("200", "获取失败未找到数据", list);
        }
    }


    @Login
    @RequestMapping(value = {"/save"}, method = {RequestMethod.POST})
    @ResponseBody
    public JsonData save(LbbCommon task, TaskScreenshot taskScreenshot,@RequestParam(value = "file", required = false) MultipartFile file,
                         HttpServletRequest request, HttpServletResponse response, String str) {
        taskScreenshot.setCategory(TaskCategory.Common.name());
        taskScreenshot.setIsMultiword(1);
            task.setIsMultiword(1);
            task.setLessTime(0);
            task.setWaitTime(0);
            task.setWaitCount(0);
        if(TextUtil.isEmpty(task.getBussAmount())){
            task.setBussAmount(task.getIncrease());
        }
        if (null == task.getTaskId() || "".equals(task.getTaskId())) {
            String taskId = UUIDUtil.L();
            task.setTaskId(taskId);
            taskScreenshot.setTaskId(task.getTaskId());
            try {
                task.setTaskScreenshot(taskScreenshot);
                commonTaskService.insertTask(task);
                asyncs.recordToMember(task.getTitle(), taskId);
                return Callback.success("200", "上传成功!", null);
            } catch (Exception e) {
                e.printStackTrace();
                return Callback.fail("200", "上传失败!", null);
            }
        } else {
            try {
            } catch (Exception e) {
                e.printStackTrace();
                return Callback.fail("200", "上传失败!", null);
            }
            LbbCommon co = commonTaskService.taskInfoByTaskId(task.getTaskId());
            task.setId(co.getId());
            task.setTaskScreenshot(taskScreenshot);
            commonTaskService.updateTask(task);

        }
        return Callback.success("200", "上传成功!", null);
    }

    @Login
    @RequestMapping(value = "/checkList", method = {RequestMethod.GET})
    public String checkList(Model model, HttpServletRequest request, HttpSession session) {
        model.addAttribute("taskStatus", TaskStatus.values());
        return "/multiword/checkList";
    }

    @Login
    @RequestMapping(value = "/checkList", method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> getCheckList(String status, String stime, String etime, Integer offset, Integer limit,
                                            String customer, String title, HttpServletRequest request, HttpSession session, String phone) {
        String category = TaskCategory.Common.name();
        return memberRecordService.pagging(category, status, stime, etime, offset, limit, title, customer, phone, 1);
    }

    @Login
    @RequestMapping(value = "/upCheck", method = {RequestMethod.GET})
    public String upCheck(Model model, HttpServletRequest request, HttpSession session) {
        // commonService.get
        List<Map<String, Object>> a = commonComponent.task(1);// 获取soso和common全部上架的taskid
        model.addAttribute("task", a);
        model.addAttribute("taskStatus", TaskStatus.values());
        return "/multiword/upCheck";
    }



    @Login
    @RequestMapping(value = {"/delData"}, method = {RequestMethod.POST})
    @ResponseBody
    public String delData(@RequestParam(value = "taskId", required = false) String taskId, HttpServletRequest request,
                          HttpServletResponse response) {
        commonComponent.delDate();
        return "已清除";
    }





    @Login
    @RequestMapping(value = "/getPhone", method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> getPhone(String taskId, String stime, String etime, HttpServletRequest request,
                                        HttpSession session) {
        return memberRecordService.getPhone(taskId, stime, etime);
    }

    @Login
    @RequestMapping(value = "/none", method = {RequestMethod.POST}) // 查不到用户
    @ResponseBody
    public Map<String, Object> none(String taskId, String stime, String etime, HttpServletRequest request,
                                    HttpSession session) {
        return memberRecordService.none(taskId, stime, etime);
    }

    @Login
    @RequestMapping(value = "/checkFailure", method = {RequestMethod.POST}) // 无匹配到的 多余的任务记录
    @ResponseBody
    public Map<String, Object> checkFailure(String taskId, String stime, String etime, HttpServletRequest request,
                                            HttpSession session) {
        return memberRecordService.checkFailure(taskId, stime, etime);
    }

    @Login
    @RequestMapping(value = "/checkSuccess", method = {RequestMethod.POST}) // 成功
    @ResponseBody
    public Map<String, Object> checkSuccess(String taskId, String stime, String etime, HttpServletRequest request,
                                            HttpSession session) {
        return memberRecordService.checkSuccess(taskId, stime, etime);
    }

    @Login
    @RequestMapping(value = "/check/{memberid}/{taskid}", method = {RequestMethod.GET})
    public String check(@PathVariable(value = "memberid") String memberid,
                        @PathVariable(value = "taskid") String taskid, Model model, HttpServletRequest request,
                        HttpSession session) {
        LbbMemberRecord record = memberRecordService.checkRecord(memberid, taskid, TaskCategory.Common.name());
        if (record != null) {
            model.addAttribute("result", JSONArray.parseArray(record.getResult()));
            model.addAttribute("task", commonTaskService.taskInfoByTaskId(taskid));
            LbbMember member = memberService.getMemberByMemberId(record.getMemberId());
            if (member != null) {
                model.addAttribute("member", member);
            }
        }
        return "/multiword/check";
    }


    @Login
    @RequestMapping(value = "/detail", method = {RequestMethod.POST})
    @ResponseBody
    public Object detail(@RequestParam(value = "memberid") String memberid,
                         @RequestParam(value = "taskid") String taskid, HttpServletRequest request, HttpSession session) {
        LbbMemberRecord record = memberRecordService.checkRecord(memberid, taskid, TaskCategory.Common.name());
        if (record == null) {
            return "记录不存在！";
        }
        return record;
    }

    @Login
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/export", method = {RequestMethod.GET, RequestMethod.POST})
    public void exports(@RequestParam(value = "taskid") String taskid,
                        @RequestParam(value = "upStatus") String upStatus, HttpServletRequest request, HttpServletResponse response,
                        HttpSession session) {
        try {
            LbbCommon task = commonTaskService.taskInfoByTaskId(taskid);
            if (task == null) {
                return;
            }
            if (upStatus == null) {
                return;
            }
            if (upStatus.equals(TaskStatus.WaitCheckout.name()) || "WaitCheckout".equals(upStatus)) {
                List<LbbMemberRecord> records = memberRecordService.getRecord(taskid, TaskStatus.WaitCheckout, TaskCategory.Common);
                List<Map<String, Object>> data = new ArrayList<>();
                Map<String, String> cols = new LinkedHashMap<>();
                for (LbbMemberRecord record : records) {
                    String strRecrd = JSON.toJSONString(record);
                    Map<String, Object> json = JSON.parseObject(strRecrd);
                    String result = record.getResult();
                    JSONArray array = JSONArray.parseArray(result);
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject j = array.getJSONObject(i);
                        cols.put("pic" + i, "截图" + (i + 1));
                        String url = j.get("resultImage") + "";// {"image":"http://hotbb.repinchen.cn/common_069221180976bd3a105ff8691750709d.png","title":"图例2"}
                        JSONObject ob = JSONObject.parseObject(url);
                        if (ob == null || ob.isEmpty()) {
                            continue;
                        }
                        String url1 = ob.getString("image");
                        json.put("pic" + i, url1);
                    }
                    for (int i = 1; i < array.size(); i++) {
                        JSONObject j = array.getJSONObject(i);
                        cols.put("pic1" + (i + 1), "步骤" + (i + 1));
                        String url2 = j.get("resultInput") + "";
                        json.put("pic1" + (i + 1), url2);
                    }
                    LbbMember member = memberService.getMemberByMemberId(record.getMemberId());
                    if (member == null) {
                        continue;
                    }
                    json.put("createTime", DateUtil.dateToString(record.getCreateTime(), "yyyy-MM-dd HH:mm"));
                    json.put("phone", member.getPhone());
                    json.put("status", record.getStatus().getTitle());
                    data.add(json);
                }
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + URLEncoder.encode(task.getTitle(), "utf-8") + ".xls ");
                Map<String, String> columns = new LinkedHashMap<>();
                columns.put("status", "审核结果");
                columns.put("createTime", "任务时间");
                columns.put("phone", "手机号");
                columns.put("imei", "设备标识");
                columns.putAll(cols);
                ExeclUtil.write(columns, data, response.getOutputStream());
            } else {
                List<LbbMemberRecord> records = memberRecordService.getRecord(taskid, TaskStatus.CheckSuccess, TaskCategory.Common);
                List<LbbMemberRecord> record2 = memberRecordService.getRecord(taskid, TaskStatus.CheckFailure, TaskCategory.Common);
                records.addAll(record2);
                List<Map<String, Object>> data = new ArrayList<>();
                Map<String, String> cols = new LinkedHashMap<>();
                for (LbbMemberRecord record : records) {
                    String strRecrd = JSON.toJSONString(record);
                    Map<String, Object> json = JSON.parseObject(strRecrd);
                    String result = record.getResult();
                    JSONArray array = JSONArray.parseArray(result);
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject j = array.getJSONObject(i);
                        cols.put("pic" + i, "截图" + (i + 1));
                        String url = j.get("resultImage") + "";// {"image":"http://hotbb.repinchen.cn/common_069221180976bd3a105ff8691750709d.png","title":"图例2"}
                        JSONObject ob = JSONObject.parseObject(url);
                        if (ob == null || ob.isEmpty()) {
                            continue;
                        }
                        String url1 = ob.getString("image");
                        json.put("pic" + i, url1);
                    }
                    for (int i = 1; i < array.size(); i++) {
                        JSONObject j = array.getJSONObject(i);
                        cols.put("pic1" + (i + 1), "步骤" + (i + 1));
                        String url2 = j.get("resultInput") + "";
                        json.put("pic1" + (i + 1), url2);
                    }
                    LbbMember member = memberService.getMemberByMemberId(record.getMemberId());
                    if (member == null) {
                        continue;
                    }
                    json.put("createTime", DateUtil.dateToString(record.getCreateTime(), "yyyy-MM-dd HH:mm"));
                    json.put("phone", member.getPhone());
                    json.put("status", record.getStatus().getTitle());
                    data.add(json);
                }
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + URLEncoder.encode(task.getTitle(), "utf-8") + ".xls ");
                Map<String, String> columns = new LinkedHashMap<>();
                columns.put("status", "审核结果");
                columns.put("createTime", "任务时间");
                columns.put("phone", "手机号");
                columns.put("imei", "设备标识");
                columns.putAll(cols);
                ExeclUtil.write(columns, data, response.getOutputStream());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量审核入口
     **/
    @PostMapping("/checkselectlist")
    @ResponseBody
    @Login
    public JsonData checklist(HttpServletRequest request, String data, String tab, @RequestParam(value = "status") String status, @RequestParam(value = "remark", required = false) String remark) {
        List<String> list = Arrays.asList(data.split(","));
        return commonComponent.checkList(list, tab, status, remark);
    }

    @Login

    @RequestMapping(value = "/check", method = {RequestMethod.POST})
    @ResponseBody
    public String checks(@RequestParam(value = "memberid") String memberid,
                         @RequestParam(value = "taskid") String taskid, @RequestParam(value = "status") String status,
                         @RequestParam(value = "remark", required = false) String remark, Long id, HttpServletRequest request,
                         HttpSession session) {
        String uuid = UUIDUtil.M();
        boolean lock = redisClient.tryGetDistributedLock("lock:common:" + taskid, uuid, 10000);
        if (!lock) {
            return "操作失败请重试";
        }
        LbbMemberRecord record = memberRecordService.checkRecord(memberid, taskid, TaskCategory.Common.name());
        if (record == null) {
            return "任务不存在！";
        }
        if (record.getStatus().equals(TaskStatus.CheckSuccess)) {
            return "任务已审核通过，不能再审核！";
        }
        LbbMemberRecord memberRecord = new LbbMemberRecord();
        memberRecord.setId(record.getId());
        memberRecord.setStatus(TaskStatus.getByTitle(status));

        LbbCommon task = commonTaskService.taskInfoByTaskId(taskid);
        record.setStatus(TaskStatus.getByTitle(status));
        if (record.getStatus().equals(TaskStatus.CheckFailure)) {
            record.setRemark(remark);
            memberRecord.setRemark(remark);
        }
        memberRecordService.updateByPrimaryKeySelective(memberRecord);
        if (record.getStatus().equals(TaskStatus.CheckSuccess)) {
            // 计算奖励
            Integer amount ;
            if(record.getUserMoney().equals(0)){
                amount = AmountUtil.checkAmount(task);
            }else {
                amount=record.getUserMoney();
            }
            if (task.getIsMultiword() == 1) {
                int index = 0;
                boolean p = false;
                MultiwordSpeech multiwordSpeech = multiwordServiceImpl.getMultiwordSpeechById(record.getOrderId());
                int i1 = 0;
                int o = 0;
                if (multiwordSpeech.getHasPlan() == 1) {
                    String str = DateUtil.dateToString(record.getCreateTime(), "yyyyMMdd");
                    MultiwordSpeechPlan plan = multiwordServiceImpl.getmultiwordSpeech(multiwordSpeech.getId(), str);
                    if (plan != null) {
                        plan.setTadayTotal(plan.getTadayTotal() + 1);
                        o = multiwordServiceImpl.updateMultiwordSpeechPlain(plan);
                    }
                    multiwordSpeech.setAllTotal(multiwordSpeech.getAllTotal() + 1);
                    multiwordSpeech.setTadayTotal(multiwordSpeech.getTadayTotal() + 1);
                    i1 = multiwordServiceImpl.updateMultiwordSpeech(multiwordSpeech);
                } else {
                    o = 1;
                    multiwordSpeech.setAllTotal(multiwordSpeech.getAllTotal() + 1);
                    multiwordSpeech.setTadayTotal(multiwordSpeech.getTadayTotal() + 1);
                    i1 = multiwordServiceImpl.updateMultiwordSpeech(multiwordSpeech);
                }
            }

            walletService.income(record.getMemberId(), record, TaskCategory.Common, taskid.toString(), task.getTitle(), amount);
            //memberNoticeService.notice(record, task.getTitle(), "任务通知:提交的任务审核成功!");
        } else {

            memberNoticeService.notice(record, task.getTitle(), "对不起，您提交的不符合要求，审核失败!");
        }
        redisClient.releaseDistributedLock("lock:common:" + taskid, uuid);
        return "审核完成!";
    }

    //搜索关键字分页跳转
    @Login
    @GetMapping("/speechlist")
    public String speechpaggingl(Integer id, Model model) {
        model.addAttribute("id", id);
        return "/multiword/speechlist";
    }

    //搜索关键字分页数据
    @Login
    @PostMapping("/speechlist")
    @ResponseBody
    public Map<String, Object> speeching(HttpServletRequest request, Integer id, Integer offset, Integer limit) {
        Map<String, Object> data = commonComponent.speechPaging(id, offset, limit);
        return data;
    }

    //搜索关键字计划分页跳转
    @GetMapping("/speechplanlist")
    public String speechingPlan(Integer id, Model model) {
        model.addAttribute("id", id);
        return "/multiword/speechplan";
    }

    //搜索关键字计划分页数据
    @Login
    @PostMapping("/speechplanlist")
    @ResponseBody
    public Map<String, Object> speechingPlan(Integer id, Integer offset, Integer limit) {
        Map<String, Object> data = commonComponent.speechPagingPlan(id, offset, limit);
        return data;
    }

    //关键字新增修改
    @Login
    @GetMapping("/speechinsert")
    public String speechingInsert(Long commonid, Model model, Long id) {
        if (id != null) {
            model.addAttribute("item", multiwordServiceImpl.getMultiwordSpeechById(id));
        } else {
            // model.addAttribute("commonid",commonid);
            MultiwordSpeech item = new MultiwordSpeech();
            item.setMultiwordId(commonid);
            model.addAttribute("item", item);
        }


        return "/multiword/speech-edit";
    }

    //执行计划新增修改
    @GetMapping("/speechplaninsert")
    @Login
    public String speechingPlanInsert(Integer speechid, Model model, Integer id) {
        if (id != null) {
            model.addAttribute("item", multiwordServiceImpl.getMultiwordSpeechplanById(id));
        } else {
            MultiwordSpeechPlan item = new MultiwordSpeechPlan();
            item.setMultiwordSpeechId(speechid);
            model.addAttribute("item", item);
        }

        return "/multiword/speechplan-edit";
    }

    //搜索关键字保存
    @PostMapping("/speechinsert")
    @ResponseBody
    @Login
    public JsonData speechingPlanEdit(MultiwordSpeech data) {
        if (data.getAmount() < 0) {
            return Callback.fail("200", "每日量不能小于0", null);
        }
        if (data.getTotal() < 0) {
            return Callback.fail("200", "总量不能小于0", null);
        }

        if (data.getAmount() != 0 && data.getAmount() > data.getTotal()) {
            return Callback.fail("200", "每日量不能大于总量", null);
        }
        return multiwordServiceImpl.editMultiwordSpeech(data);
    }

    //执行计划保存
    @PostMapping("/speechplaninsert")
    @ResponseBody
    @Login
    public JsonData speechingPlanEdit(MultiwordSpeechPlan item) {
        return multiwordServiceImpl.editMultiwordSpeechplan(item);
    }

    //关键字逻辑删除
    @PostMapping("/speechdelete")
    @ResponseBody
    @Login
    public JsonData speechDelete(HttpServletRequest request, Integer id) {
        return multiwordServiceImpl.speechdelete(id);
    }

    //执行计划逻辑删除
    @PostMapping("/speechplandelete")
    @ResponseBody
    @Login
    public JsonData speechingPlanDelete(HttpServletRequest request, Integer id) {
        return multiwordServiceImpl.speechplandelete(id);
    }
    @PostMapping("/reload")
    @ResponseBody
    public JsonData taskReload(String taskId) {
        LbbCommon common = commonTaskService.taskInfoByTaskId(taskId);
        if (common != null) {
            List<LbbCommon> commons = new ArrayList<>();
            commons.add(common);
            List<MultiwordSpeech> mslist = multiwordServiceImpl.getMultiwordSpeech(common.getId());
            if (multiwordServiceImpl.startaskamountr(mslist)) {
                return Callback.success("success", "操作成功", null);
            } else {
                return Callback.fail("fail", "操作失败", null);
            }
        }
        return Callback.fail("fail", "操作失败", null);
    }
    @PostMapping("/starMultiwordTask")
    @ResponseBody
    public JsonData starMultiwordTask() {

        if (multiwordServiceImpl.starTaskAmount(LocalDateTime.now())) {
            return Callback.success("success", "操作成功", null);
        } else {
            return Callback.fail("fail", "操作失败", null);
        }
    }


    @Login
    @RequestMapping(value = {"/copyData/{taskid}"}, method = {RequestMethod.GET})
    public String copyDataInsert(@PathVariable(value = "taskid") String taskid, Model model, HttpSession session) {
        model.addAttribute("rewards", RewardMode.values());
        model.addAttribute("types", RewardType.values());
        LbbCommon task = commonTaskService.taskInfoByTaskId(taskid);
        task.setId(null);
        task.setTaskId(null);
        TaskScreenshot taskScreenshot = taskScreenshotService.selectByTaskId(taskid);
        model.addAttribute("tags",taskScreenshotService.selectRelation(taskid));
        model.addAttribute("taskScreenshot",taskScreenshot);
        model.addAttribute("task", task);
        model.addAttribute("customlist", customService.getAllCustomList());
        model.addAttribute("taskClassifys",taskClassifyService.selectByExample(null));
        model.addAttribute("taskTags",taskTagService.selectByExample(null));
        return "/multiword/edit";
    }

}
